package com.lcz.mytest.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lcz.mytest.domain.User;

import java.util.ArrayList;
import java.util.List;

/*用户数据库操作类*/
public class UserService {
    private DatabaseHelper dbHelper;
    private SQLiteDatabase sd;
    private String code;
    private String datatype;

    public UserService(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    // 登录用
    public boolean login(String username, String password) {
        sd = dbHelper.getReadableDatabase();
//        String sql = "select * from user where username=? and password=?";
//        Cursor cursor = sd.rawQuery(sql, new String[]{username, password});
        Cursor cursor = sd.query("user", null, "username=? and password=?", new String[]{username, password}, null, null, null);
        if (cursor.moveToFirst() == true) {
            cursor.close();
            return true;
        }
        return false;
    }

    // 注册用
    public boolean register(User user) {
        sd = dbHelper.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("username", user.getName());
        cv.put("password", user.getPassword());
        sd.insert("user", null, cv);

        /*String sql = "insert into user(username,password) values(?,?)";
        Object obj[] = {user.getName(), user.getPassword()};
        sd.execSQL(sql, obj);*/
        return true;
    }

    //收藏个股
    public boolean collect(User user) {
        sd = dbHelper.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("username", user.getName());
        cv.put("stockcode", user.getStockCode());
        cv.put("datatype", user.getDataType());
        sd.insert("collect", null, cv);
        return true;
    }

    //删除收藏
    public boolean deleteCollect(User user) {
        sd = dbHelper.getWritableDatabase();
        int i = sd.delete("collect", "username = ?and stockcode = ?and datatype = ? ", new String[]{user.getName(), user.getStockCode(), user.getDataType()});
        if (i ==0){
            return true;
        }else {
            return false;
        }
    }

    //查询收藏列表
    public List<User> collectList(String name) {
        sd = dbHelper.getReadableDatabase();
        Cursor cursor = sd.query("collect", null, "username=?", new String[]{name}, null, null, null);
        List<User> list = new ArrayList<>();

        if (cursor!=null){
            while (cursor.moveToNext()) {
                code = cursor.getString(cursor.getColumnIndex("stockcode"));
                datatype = cursor.getString(cursor.getColumnIndex("datatype"));
                User user = new User();
                user.setStockCode(code);
                user.setDataType(datatype);
                list.add(user);
            }
        }
        return list;
    }
}
